﻿using System;
using System.IO;
using System.Data;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;
using ESRI.ArcGIS.Geodatabase;
using PlanningGIS.DataConvert.model;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.DataSourcesGDB;
using Microsoft.VisualBasic;

using DevComponents.DotNetBar;
using PlanningGIS.Framework.Controls;
using PlanningGIS.Framework;
using PlanningGIS.Engine.Controls;
using PlanningGIS.ArcGIS.Custom;
using PlanningGIS.Win.Controls;
using PlanningGIS.Util.Convertor;
using PlanningGIS.Util.Log;

namespace PlanningGIS.DataConvert.form
{
    /// <summary>
    /// 名    称：FrmRasterConvert
    /// 作    用：栅格数据转换对话框
    /// 开发人员：张利勇
    /// 开发日期：2009-06-25
    /// 修改人员：
    /// 修改日期：
    /// 修改说明：
    /// </summary>
    public partial class FrmRasterConvert : Office2007Form
    {
        public String RasterName;
        IWorkspace pRasterWorkspace = null;
        IRaster m_pRaster = null;
        string sFileNew = "";
        private OpenDataDialog openDataDialog1 = new OpenDataDialog();
        private List<IDataNode> m_DataNodes; //用户选中的数据源
        public CmdSelectDataOk SelectDataOk;
        
        IApplication m_Application = null;
        
        public FrmRasterConvert(IApplication value)
        {
            m_Application = value;
            InitializeComponent();

            combo_SaveFormat.SelectedIndex = 0;
        }

        /// <summary>
        /// 选择文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenTargetWS_Click(object sender, EventArgs e)
        {
            if (combo_SaveFormat.Text == "GRID")
            {
                FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
                folderBrowserDialog.Description = "选择栅格转换输出路径";
                if (folderBrowserDialog.ShowDialog(this) == DialogResult.OK)
                {
                    string path = folderBrowserDialog.SelectedPath;

                    IWorkspaceFactory pWF = new RasterWorkspaceFactoryClass();
                    txtTargetWS.Text = path;

                    pRasterWorkspace = pWF.OpenFromFile(path, 0);// _folder指栅格文件保存路径
                }
            }
            else
            {
                string sPath = "";

                if (combo_SaveFormat.Text == "TIFF")
                {
                    saveFileDialog1.Filter = "TIFF(*.tif)|*.tif";
                }
                else if (combo_SaveFormat.Text == "IMAGINE Image")
                {
                    saveFileDialog1.Filter = "IMAGINE Image(*.img)|*.img";
                }
                saveFileDialog1.FilterIndex = 1;
                saveFileDialog1.RestoreDirectory = true;
                saveFileDialog1.Title = "请选择保存路径";

                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    if (saveFileDialog1.FileName != "")
                    {
                        sPath = saveFileDialog1.FileName;
                        txtTargetWS.Text = sPath;
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }

                int iL = sPath.LastIndexOf("\\");
                string sFolder = sPath.Substring(0, iL);
                IWorkspaceFactory pWF = new RasterWorkspaceFactoryClass();
                pRasterWorkspace = pWF.OpenFromFile(sFolder, 0);
                sFileNew = sPath.Substring(iL + 1, sPath.Length - iL - 1);
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetDefaultNewName();
        }

        private void GetDefaultNewName()
        {
            //    if (combo_SaveFormat.Text == "TIFF")
            //    {
            //        combo_SaveFormat.Enabled = true;
            //        text_FileName.Text = RasterName + ".tif";
            //    }
            //    else if (combo_SaveFormat.Text == "IMAGINE Image")
            //    {
            //        combo_SaveFormat.Enabled = true;
            //        text_FileName.Text = RasterName + ".img";
            //    }
            //    else if (combo_SaveFormat.Text == "GRID")
            //    {
            //        combo_SaveFormat.Enabled = true;
            //        text_FileName.Text = RasterName;
            //    }
            if (combo_SaveFormat.Text == "GRID")
            {
                text_FileName.Enabled = true;
                text_FileName.Text = RasterName;
            }
            else
            {
                text_FileName.Enabled = false;
            }
            txtTargetWS.Text = "";
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (text_Raster.Text.Trim().Length == 0)
            {
                MsgHelper.ShowWarningMsgbox("请选择栅格数据");
                return;
            }

            if (pRasterWorkspace == null)
            {
                MsgHelper.ShowWarningMsgbox("请选择栅格转换路径");
                return;
            }

            if (txtTargetWS.Text.Trim().Length == 0)
            {
                MsgHelper.ShowWarningMsgbox("请选择栅格转换路径");
                return;
            }

            if (this.combo_SaveFormat.Text == "GRID" && text_FileName.Text.Trim().Length == 0)
            {
                MsgHelper.ShowWarningMsgbox("新文件名不能为空！");
                return;
            }

            String NewName = "";
            if (this.combo_SaveFormat.Text == "GRID")
                NewName = text_FileName.Text.Trim();
            else
                NewName = sFileNew;

            if ((combo_SaveFormat.Text == "GRID") && (StringHelper.TextLength(NewName) > 9) && (pRasterWorkspace.Type == esriWorkspaceType.esriFileSystemWorkspace))
            {
                MsgHelper.ShowErrorMsgbox("GRID保存为文件时文件名不能超过9位，请先修改文件名!");
                return;
            }

            if (pRasterWorkspace.Type == esriWorkspaceType.esriFileSystemWorkspace)
            {
                IEnumDataset datasets = pRasterWorkspace.get_Datasets(esriDatasetType.esriDTRasterDataset);
                IDataset pDataset = null;
                while ((pDataset = datasets.Next()) != null)
                {
                    if (pDataset is IRasterDataset)
                    {
                        IRasterDataset pRasterDataset = (IRasterDataset)pDataset;
                        if (pRasterDataset.CompleteName.EndsWith(NewName))
                        {
                            MsgHelper.ShowErrorMsgbox(pRasterDataset.CompleteName + " 已存在，请先修改文件名!");
                            return;
                        }
                    }
                }
            }

            System.Windows.Forms.Cursor TCursor = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            try
            {
                if (pRasterWorkspace.Type == esriWorkspaceType.esriFileSystemWorkspace)
                {
                    LogHelper.WriteLog("正在进行栅格数据格式转换...");

                    RasterDataConvert pRasterDataConvert = new RasterDataConvert();
                    IRasterDataset pRasterDataset = pRasterDataConvert.SaveAs(m_pRaster, pRasterWorkspace, NewName, combo_SaveFormat.Text);   //RasterConvert(m_RasterLayer, pRasterWorkspace, text_FileName.Text.Trim(), combo_SaveFormat.Text);
                    this.Cursor = TCursor;
                    if (pRasterDataset == null)
                    {
                        MsgHelper.ShowErrorMsgbox("转换失败，请检查转换路径!");
                    }
                    else
                    {
                        MsgHelper.ShowInfomationMsgbox("转换成功！");
                    }
                    LogHelper.WriteLog("栅格数据格式转换成功。");
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLog("栅格数据格式转换失败：" + ex.Message);
            }
            this.Cursor = TCursor;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private string GetGpDsPath(IFeatureClass pFcls)
        {
            IDataset pDst = pFcls as IDataset;
            string strFclsPath = "";
            string strInput;
            switch (pDst.Workspace.Type)
            {
                case esriWorkspaceType.esriFileSystemWorkspace:
                    strFclsPath = pDst.Workspace.PathName;
                    strInput = strFclsPath + "\\" + pDst.Name + ".shp";
                    break;
                case esriWorkspaceType.esriLocalDatabaseWorkspace:
                    strFclsPath = pDst.Workspace.PathName;
                    strInput = strFclsPath + "\\" + pDst.Name;
                    break;
                case esriWorkspaceType.esriRemoteDatabaseWorkspace:
                    string strSdeFile = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\temp.sde";
                    if (!File.Exists(strSdeFile))
                    {
                        IWorkspaceFactory pWksFac = new SdeWorkspaceFactoryClass();
                        pWksFac.Create(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location), "temp.sde", pDst.Workspace.ConnectionProperties, 0);
                    }
                    strInput = strSdeFile + "\\" + pDst.Name;
                    break;
                default:
                    {
                        return "";
                    }
            }
            return strInput;
        }

        private void btn_SelectRaster_Click(object sender, EventArgs e)
        {
            openDataDialog1.MultiSelect = false;
            openDataDialog1.ShowDialog(this);

            //try
            //{
            //    OpenDataDialog dialog = new OpenDataDialog();
            //    dialog.AllowMultiSelect = false;
            //    dialog.RestoreLocation = false;
            //    IGWObjectFilter filter = new GWFilterRasterDatasets();
            //    dialog.AddFilter(filter, true);
            //    dialog.Title = "选择影像数据";
            //    if ((dialog.ShowDialog() == DialogResult.OK) && (dialog.Selection.Count != 0))
            //    {
            //        text_Raster.Text = "";
            //        m_pRaster = null;

            //        IGWObject obj2 = dialog.Selection[0];
            //        IDataset dataset = ((IName)obj2.DatasetName).Open() as IDataset;
            //        IGeoDataset dataset2 = dataset as IGeoDataset;
            //        if (dataset2 is IRasterDataset)
            //        {
            //            IRasterLayer pRasterLay = new RasterLayerClass();
            //            pRasterLay.CreateFromDataset(dataset2 as IRasterDataset);
            //            m_pRaster = pRasterLay.Raster;
            //            RasterName = pRasterLay.Name;
            //            if (RasterName.Length > 4)
            //            {
            //                if (RasterName.IndexOf(".", 0) > 0)
            //                {
            //                    RasterName = RasterName.Substring(0, RasterName.IndexOf(".", 0));
            //                }
            //            }
            //            text_Raster.Text = pRasterLay.FilePath;
            //            GetDefaultNewName();
            //        }
            //        else
            //        {
            //            MsgHelper.ShowErrorMsgbox("所选数据不是本系统支持的栅格数据格式，请选择栅格数据！");
            //        }

            //    }
            //}
            //catch (Exception ex)
            //{
            //    MsgHelper.ShowErrorMsgbox("出现错误，提示信息是：" + ex.Message);
            //}
        }

        private void FrmRasterConvert_Load(object sender, EventArgs e)
        {
            openDataDialog1.OnOkClick = new EventHandler(CmdAddDataOk_Click);
        }

        public List<IDataNode> DataNodeList
        {
            get { return m_DataNodes; }
        }

        private void CmdAddDataOk_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                List<ILayer> pRstLyrs = openDataDialog1.GetRasterDatasetLyrs();
                //List<ILayer> pRstLyrs = openDataDialog1.GetSelectLayers(esriDatasetType.esriDTRasterDataset);
                if (pRstLyrs.Count == 0)
                {
                    MsgHelper.ShowErrorMsgbox("所选数据不是本系统支持的栅格数据格式，请选择栅格数据！");
                    return;
                }

                IRasterLayer pRasterLay = pRstLyrs[0] as IRasterLayer;
                m_pRaster = pRasterLay.Raster;

                RasterName = pRasterLay.Name;

                //if (m_DataNodes == null)
                //{
                //    m_DataNodes = openDataDialog1.GetAllDataNodes();
                //}
                //else
                //{
                //    m_DataNodes.AddRange(openDataDialog1.GetAllDataNodes());
                //}

                text_Raster.Text = openDataDialog1.FullName;
                GetDefaultNewName();

                openDataDialog1.Close();
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
    }
}
